from django.shortcuts import render

# Create your views here.
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler

from users.models import User
from users.serializers import User_Serializer


class Register(APIView):
    def post(self, request):
        uname = request.data.get("uname")
        upwd = request.data.get("upwd")
        uaccount = request.data.get("uaccount")
        if not all([uname, upwd, uaccount]):
            return Response({'msg': '请输入完整的信息', 'code': 400})
        # make_pwd = make_password(pwd)
        try:
            User.objects.create(uname=uname, upwd=upwd, uaccount=uaccount)
            return Response({'msg': '注册成功', 'code': 200})
        except Exception as e:
            print(e)
            return Response({'msg': '注册失败', 'code': 400})


class Login(APIView):
    def post(self, request):
        uaccount = request.data.get("uaccount")
        pwd = request.data.get("upwd")
        try:
            user = User.objects.get(uaccount=uaccount)
        except Exception as e:
            print(e)
            return Response({"message": "没有用户", "code": 400})
        if user.upwd != pwd:
            return Response({"message": "密码错误", "code": 400})

        else:
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return Response({"message": "登录成功", "code": 200, 'token': token})

# 分页器
class Page(PageNumberPagination):
    page_size = 3  # 默认每页数目
    page_query_param = 'page'  # 页码关键字名， 默认为"page"
    page_size_query_param = 'pagesize'  # 每页数目关键字名, ，默认为None

# 用户的增删改查
class UserView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = User_Serializer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"
    pagination_class = Page




